package io.gitee.kotle.android.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.airbnb.lottie.LottieAnimationView
import io.gitee.kotle.android.delegate.unsafeLazy

/**
 *
 * 描述：
 *
 * @author jiale.wei
 *
 * 创建时间：2022/7/5 13:38
 *
 */
class LottieLayout : RatioLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    val lottie by unsafeLazy { LottieAnimationView(context) }
    private val fl by unsafeLazy { FrameLayout(context) }

    init {
        addView(lottie)
        addView(fl)
    }


    private var scaleFloat = 1f

    /**
     * 设置动画宽高
     */
    fun setJsonAnimSize(w: Int, h: Int) {
        checkHasSize {
            setChildRatio(w.toFloat() / h)
            scaleFloat = lottie.width / w.toFloat()
        }
    }

    /**
     * 设置虚拟的view
     */
    fun setVirtualView(view: View, imageW: Int, imageH: Int, imageX: Int, imageY: Int) {
        checkHasSize {
            val lp = LayoutParams(imageW.getRealSize(), imageH.getRealSize())
            lp.marginStart = imageX.getRealSize()
            lp.topMargin = imageY.getRealSize()
            fl.addView(view, lp)
        }
    }

    /**
     * 移除虚拟view
     */
    fun removeVirtualView(view: View) {
        fl.removeView(view)
    }

    private fun Int.getRealSize() = (this * scaleFloat).toInt()

    /**
     * 检查size
     */
    private fun checkHasSize(block: Runnable) {
        if (fl.width == 0 || fl.height == 0) {
            fl.post(block)
        } else {
            block.run()
        }
    }
}